﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using HAF.FoundationLib;
using Newtonsoft.Json;
using WareDealer.Helper;
using WareDealer.Mode;

namespace WareDealer.Works
{
    /// <summary>
    /// 商品配送区域工作项
    /// </summary>
    [DisplayName("商品配送区域工作项")]
    public class JdDispatchAreaWork : ProcessItem
    {
        public override void ExecItem()
        {
            ShowAutoMessage("采集商品地区信息开始！");
            GetAreas(0, 0);
            ShowAutoMessage("商品地区信息入库");
            DbHelper.GetInstance().AreaAdd(WareAreas);
            EndAutoProcess("main", true);
        }

        readonly List<DispatchArea> WareAreas = new List<DispatchArea>();

        private List<DispatchArea> GetAreas(int id, int iLevel)
        {
            try
            {
                string url = string.Format("http://d.jd.com/area/get?fid={0}", id);
                string rtnStr = HttpHelper.GetResponseGBK(url, "get", string.Empty);
                if (string.IsNullOrEmpty(rtnStr) || rtnStr.IndexOf("error", StringComparison.Ordinal) >= 0)
                {
                    return null;
                }
                List<DispatchArea> nowList = JsonConvert.DeserializeObject<List<DispatchArea>>(rtnStr);

                if (id == 0)
                {
                    nowList.ForEach(t => t.ParentID = -1);
                    InitAutoProcess("main", nowList.Count);
                    WareAreas.AddRange(nowList ?? new List<DispatchArea>());
                }
                int myLevel = iLevel + 1;
                int iStep = 1;
                if (myLevel < 3)
                {
                    foreach (var item in nowList)
                    {
                        if (myLevel == 1)
                        {
                            ShowAutoMessage(string.Format("获取{0}数据", item.Name));
                            ShowAutoStep("main", iStep);
                            iStep++;
                            if (item.id > 100)
                            {
                                continue;
                            }
                        }

                        List<DispatchArea> rtnAreas = GetAreas(item.id, myLevel);
                        foreach (var rtnItem in rtnAreas)
                        {
                            rtnItem.ParentID = item.id;
                            rtnItem.Level = myLevel;
                        }
                        WareAreas.AddRange(rtnAreas ?? new List<DispatchArea>());
                        Thread.Sleep(600);
                    }
                }
                return nowList;
            }
            catch (Exception ex)
            {
                Faster.XLogErr(ex.Message);
                return null;
            }

        }
    }
}
